from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

app = FastAPI()

# 加载Qwen3模型与分词器（只执行一次）
tokenizer = AutoTokenizer.from_pretrained(
    "./Qwen3-1.7b", trust_remote_code=True)
if torch.cuda.is_available():
    model = AutoModelForCausalLM.from_pretrained(
        "./Qwen3-1.7b", trust_remote_code=True).eval().cuda()
else:
    model = AutoModelForCausalLM.from_pretrained(
        "./Qwen3-1.7b", trust_remote_code=True).eval()

# 定义请求结构（模仿OpenAI接口）
class Message(BaseModel):
    role: str
    content: str

class ChatRequest(BaseModel):
    model: str
    messages: list[Message]
    max_tokens: int = 512
    temperature: float = 0.7

@app.post("/v1/chat/completions")
def chat(req: ChatRequest):
    # 拼聊天格式
    history = []
    for msg in req.messages:
        if msg.role == 'user':
            history.append({"role": "user", "content": msg.content})
        elif msg.role == 'assistant':
            history.append({"role": "assistant", "content": msg.content})
    prompt = tokenizer.apply_chat_template(
        history, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=req.max_tokens,
            temperature=req.temperature,
            do_sample=True,
            pad_token_id=tokenizer.pad_token_id,
        )
    answer = tokenizer.decode(outputs[0], skip_special_tokens=True)[len(prompt):].strip()
    return {
        "choices": [
            {"message": {"role": "assistant", "content": answer}}
        ]
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)